package com.hmall.item.es;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.item.domain.dto.ItemDoc;
import com.hmall.item.domain.po.Item;
import com.hmall.item.service.IItemService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

@SpringBootTest(properties = "spring.profiles.active=local")
public class ElesticDocumentText {

    private RestHighLevelClient client;

    @Autowired
    private IItemService itemService;

    // 测试索引库的连接
    @Test
    public void testIndex(){
        System.out.println("hello client = " + client);
    }


    //测试创建文档
    @Test
    public void testIndexDoc() throws IOException {
        //0.1 准备数据实体类
        Item item = itemService.getById(2120808L);
        //2、将item类型的数据复制到item Doc类中
        ItemDoc itemDoc = BeanUtil.copyProperties(item, ItemDoc.class);

        // 1、创建Request
        IndexRequest market = new IndexRequest("market").id(itemDoc.getId());
        //2、 添加请求参数
        market.source(JSONUtil.toJsonStr(itemDoc), XContentType.JSON);
        //3、发送请求
        client.index(market, RequestOptions.DEFAULT);
    }

    // 测试查询文档
    @Test
    public void testGetDoc() throws IOException {
        //1、创建Request
        GetRequest market = new GetRequest("market","2120808");
        //2、发送请求，得到结果
        GetResponse response = client.get(market, RequestOptions.DEFAULT);
        //3、解析结果
        String json = response.getSourceAsString();

        ItemDoc doc = JSONUtil.toBean(json, ItemDoc.class);
        System.out.println("doc = " + doc);
    }

    // 测试删除文档
    @Test
    public void testDeleteDoc() throws IOException {
        //1、创建Request
        DeleteRequest market = new DeleteRequest("market","2120808");
        //2、发送请求
        client.delete(market, RequestOptions.DEFAULT);
    }

    // 测试修改文档
    // 全局修改  跟新增完全一样
    @Test
    public void testUpdateeDoc() throws IOException {
        //0.1 准备数据实体类
        Item item = itemService.getById(2120808L);
        //2、将item类型的数据复制到item Doc类中
        ItemDoc itemDoc = BeanUtil.copyProperties(item, ItemDoc.class);

        itemDoc.setPrice(51000);

        // 1、创建Request
        IndexRequest market = new IndexRequest("market").id(itemDoc.getId());
        //2、 添加请求参数
        market.source(JSONUtil.toJsonStr(itemDoc), XContentType.JSON);
        //3、发送请求
        IndexResponse index = client.index(market, RequestOptions.DEFAULT);
        System.out.println("index = " + index);
    }

    // 局部修改
    @Test
    public void testUpdateDoc2() throws IOException {
        // 1、创建Request
        UpdateRequest market = new UpdateRequest("market","2120808");
        //2、 添加请求参数
        market.doc("price",50000);
        //3、发送请
        client.update(market, RequestOptions.DEFAULT);
    }

    //批处理
    @Test
    public void testPulkDoc() throws IOException {
        int pageNo = 1;
        int pageSize = 500;
        while (true) {
            //分页查询数据库中的所有数据
            Page<Item> page = itemService.lambdaQuery()
                    .eq(Item::getStatus, 2)//1-正常，2-下架，3-删除
                    .page(new Page<Item>(pageNo, pageSize));
            //得到每次查询的结果
            List<Item> items = page.getRecords();
            //非空校验
            if (items == null || items.size() == 0){
                return;
            }
            //1、创建Request
            BulkRequest request = new BulkRequest();
            //2、批量添加请求参数
            //遍历集合，得到每个商品的数据
            for (Item item : items) {
//                request.add(new IndexRequest("market")
//                        //设置id
//                        .id(item.getId().toString())
//                        //添加请求参数
//                        //把item转换为json
//                        //因为得到的是Item,需要先把item转换为ItemDoc用==>BeanUtil.copyProperties(item, ItemDoc.class)
//                        .source(JSONUtil.toJsonStr(BeanUtil.copyProperties(item, ItemDoc.class)), XContentType.JSON));
                request.add(new DeleteRequest("market").id(item.getId().toString()));
            }
//
//        request.add(new UpdateRequest("market","2120808").doc("price",50000));
            //3、发送请求
            client.bulk(request, RequestOptions.DEFAULT);
            //翻页
            pageNo++;
        }
    }



    @BeforeEach// 在每个测试方法之前执行
    void setUp() {
        // 创建客户端
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.253.130:9200")
        ));
    }
    @AfterEach// 在每个测试方法之后执行
    void tearDown() throws IOException {
        // 关闭客户端
        this.client.close();
    }

}
